package com.tim.openoffice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SysCmd {

	/**
	 * 执行系统命令，并返回执行结果.
	 * 
	 * @param cmdLine
	 *            系统命令字符串.
	 * @return int 执行结果. 0:执行成功,非零执行不成功.
	 */
	public static int execCommand(String cmdLine) throws IOException,
			InterruptedException {
		if (System.getProperty("os.name").matches(".*[Ww]indows.*")) {
			return exec(new String[] { "cmd", "/c", cmdLine });
		} else {
			return exec(new String[] { "sh", "-c", cmdLine });
		}
	}

	public static int exec(String[] cmdArray) throws IOException,
			InterruptedException {
		Process p = Runtime.getRuntime().exec(cmdArray);

		String line = null;
		StringBuffer result = new StringBuffer();

		BufferedReader brIn = new BufferedReader(new InputStreamReader(p
				.getInputStream()));
		while ((line = brIn.readLine()) != null) {
			result.append(line + "\n");
		}
		brIn.close();

		BufferedReader brErr = new BufferedReader(new InputStreamReader(p
				.getErrorStream()));
		while ((line = brErr.readLine()) != null) {
			result.append(line + "\n");
		}
		brErr.close();

		// 执行成功则：exitValue=0
		return p.exitValue();
	}

	public static void main(String[] args) {
		try {
			String[] cmdArr = new String[] { "javac -version", "java -version",
					"dir D:", "ping 192.168.1.1" };
			for (int i = 0; i < cmdArr.length; i++) {
				execCommand(cmdArr[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
